﻿/********************************************************************
	created:	2011/05/12
	created:	12:5:2011   21:12
	filename: 	D:\My Documents\Visual Studio 2010\Projects\IntranetMessager\ServiceLibrary\CryptoService.cs
	file path:	D:\My Documents\Visual Studio 2010\Projects\IntranetMessager\ServiceLibrary
	file base:	CryptoService
	file ext:	cs
	author:		
	
	purpose:	DES与RSA解密、加密、签名
*********************************************************************/
using System;
using System.Security.Cryptography;

namespace ServiceLibrary
{
    internal static class CryptoService
    {
        private const int KeyLength = 256;

        internal static byte[] DesEncrypt(string key, string iv, byte[] byteMessage)
        {
            using (var des = new DESCryptoServiceProvider())
            {
                if (key == null)
                {
                    return byteMessage;
                }
                var encryptor = des.CreateEncryptor(Convert.FromBase64String(key),
                                                                 Convert.FromBase64String(iv));
                return encryptor.TransformFinalBlock(byteMessage, 0, byteMessage.Length);
            }
        }

        internal static byte[] DesDecrypt(string key, string iv, byte[] byteMessage)
        {
            using (var des = new DESCryptoServiceProvider())
            {
                ICryptoTransform encryptor = des.CreateDecryptor(Convert.FromBase64String(key),
                                                                 Convert.FromBase64String(iv));
                return encryptor.TransformFinalBlock(byteMessage, 0, byteMessage.Length);
            }
        }

        internal static void DesGenerateKey(out string key, out string iv)
        {
            using (DES des = new DESCryptoServiceProvider())
            {
                des.GenerateKey();
                des.GenerateIV();
                key = Convert.ToBase64String(des.Key);
                iv = Convert.ToBase64String(des.IV);
            }
        }

/*
        internal static void RsaKeyPairGen()
        {
            using (var p = new RSACryptoServiceProvider(2048))
            {
                ServiceRepository.Printf(string.Format("Public Key only: {0}", p.ToXmlString(false)));
                ServiceRepository.Printf(string.Format("Private include: {0}", p.ToXmlString(true)));
            }
        }
*/

        internal static byte[] RsaDecrypt(byte[] byteMessage)
        {
            if (byteMessage.Length > KeyLength)
            {
                return RsaLongDecrypt(byteMessage);
            }
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(KeyPrivate);
                return rsa.Decrypt(byteMessage, false);
            }
        }

        private static byte[] RsaLongDecrypt(byte[] byteMessage)
        {
            var resBuffer = new byte[byteMessage.Length];
            var tempBuffer = new byte[KeyLength];
            int arrayLength = 0;

            for (int i = 0; i < byteMessage.Length; i += KeyLength)
            {
                Array.Copy(byteMessage, i, tempBuffer, 0, KeyLength);
                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.FromXmlString(KeyPrivate);
                    byte[] tempB = rsa.Decrypt(tempBuffer, false);
                    Array.Copy(tempB, 0, resBuffer, arrayLength, tempB.Length);
                    arrayLength += tempB.Length;
                }
            }
            return resBuffer;
        }

        internal static byte[] RsaSignHash(byte[] sha1Hash)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(KeyPrivate);
                return rsa.SignHash(sha1Hash, CryptoConfig.MapNameToOID("SHA1"));
            }
        }

        #region RSA密钥对

        private const string KeyPrivate =
            "<RSAKeyValue>" +
            "<Modulus>wtt+TFWQEG1Crbwvodp0S5p7ZpQrMnfbTZqqDAKdZnF2NR7NXvQdD/d/+xtuOTSK+sQ9iA+IToYGw9d9Ix+6R0CJRkv4rrEY30TdnTKPN+gnmXIouBCgSHlhUDfIFn1mDh78GX0R3Vb5gxAnA/EYiXAPD8nQWSfLNPChqHAMo7qn9ON4FpGfdBug2GM4oXJZuLuDAHV9manRDCbR2i4cPR4aJvefvyhbSmmJPhPyow7Osuof4g3RC/uu+jhHR/KHTSkMrqDd0hxAYqOgtsAIuKHmZELPtT7gXqlIcBkoMTqiUTngploYGv421ZPGQV7Abm7E5r2mxDQHhWRwVKriYQ==</Modulus>" +
            "<Exponent>AQAB</Exponent>" +
            "<P>/cl6FnuTLw0yBt7jCl1l3GiqaGEPLauN3nD4LVEWSZ3YyG+LuFDTE7rpAToCwDIOJEKlB2+O61/1Ui7cHFHDKzW2kFfdXB13cXnFplpf6CLTmg0dpjD0oFpsRPzyqrk+VT/CjPXV74jJ1fMl49vTFlSjXe50MyHi2JX8sm9CTLk=</P>" +
            "<Q>xI54GzFtzRWYRsGAmdyKdyEOUWNUBnIfn5VBlgUGPQdZmBrIykbUXWrB28bAZyfpC+aPODojyUkWAEoVbYdmnl2072uF7zCCwBwbe9zucCFA5yOdLTOAikOWw2qFC090EcfzJKvsaF1Yv98YIHJ+aFFavVUFOaY7tpM1hMQQfuk=</Q>" +
            "<DP>LspdwxVnjo49Qf0IGRodNKTrfjEe7kmp73AeoaRImqwKkvHV7dahBAs6+GnspejUqKTM7nEIBad8gHl5RZNhi27syPIaMuiP5BESethAxHjfUJDIfaKbB5GEUrfcOdPLhUYrJXgRyIcMx3B79OXLpltWf3P+YosF2u7UV0WiEKk=</DP>" +
            "<DQ>sL2y/jC6HPlYDfedXbzTvT86ErEQMyOXj/W0HeOyslnTlFQxTMHX35BJdQgIpjla8tqE2fhdiXdwkx4KmoxwF+MG+Wpj6qpiR8B+bihBNw6Pv8dkY+q1oJ4aCOnVbFArfHmhBs6ZK1cUoKNInJSXWdIdl7XFlwsFEqzYKOPsOVE=</DQ>" +
            "<InverseQ>TgSQzpgFC2FW9zIClWn686ttFPDOLX+oMFO1OLptwqDDPZ2Dt2BLhlv5aJeRdRiQWlvT5f2TcPbrA7tZWtVoIaSHFgsp/8Cw5VVWh8mfdKNlJQ2Nosn6BnyWM99akKTwVu35H7LsIrtA1a905rtvpicS+qpr8dfwk4h3L56aCKg=</InverseQ>" +
            "<D>GLj2hkLY22yxaA+XT4bC+JCqFXK5JFcWqPr1lj6Cr+u3XrgAwIpiYZM6Vqa9Tl6/P1/Ems21spjIpPJjOyCcZsvmXtfmvmtTx4gaQgaXKzW2SH62cdwSKf/Ue/QH2+qfFy2ROL6olJejYqCbAqIFRfLExnEJkTY+TwI00IUe5WrhHw9xqpUiU3/o+hLgRl214SMOWyPK1QNHmVnhXJpKi5Lp4tjDKy7tBip2+fSVRjnL8Jb10tCkgl0Sr4hFIpgvkjBdf785JrCXhh0rJYpMJA2IiIg5WBqvh7jQKQgqzr+yHfq6aG/EgDBZdm3cBLVq4j6BF2jhnn0u3yu0GenuQQ==</D>" +
            "</RSAKeyValue>";

/*
        private const string KeyPublic =
            "<RSAKeyValue>" +
            "<Modulus>wtt+TFWQEG1Crbwvodp0S5p7ZpQrMnfbTZqqDAKdZnF2NR7NXvQdD/d/+xtuOTSK+sQ9iA+IToYGw9d9Ix+6R0CJRkv4rrEY30TdnTKPN+gnmXIouBCgSHlhUDfIFn1mDh78GX0R3Vb5gxAnA/EYiXAPD8nQWSfLNPChqHAMo7qn9ON4FpGfdBug2GM4oXJZuLuDAHV9manRDCbR2i4cPR4aJvefvyhbSmmJPhPyow7Osuof4g3RC/uu+jhHR/KHTSkMrqDd0hxAYqOgtsAIuKHmZELPtT7gXqlIcBkoMTqiUTngploYGv421ZPGQV7Abm7E5r2mxDQHhWRwVKriYQ==</Modulus>" +
            "<Exponent>AQAB</Exponent>" + "</RSAKeyValue>";
*/

        #endregion
    }
}